package com.itheima.web.filter;

import com.itheima.domain.SysLog;
import com.itheima.factory.BeanFactory;
import com.itheima.service.SysLogService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//@WebFilter("/*")
public class AuthorFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.定义和协议相关的请求和响应对象
        HttpServletRequest request;
        HttpServletResponse response;
        HttpSession session;
        try {
            //2.把参数转换成协议相关的对象
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) resp;
            session = request.getSession();

            //1.获取本次操作
            String url = request.getRequestURI();
            //.css   .js    .png   .jpg   .index
            if (url.endsWith(".css")
                    || url.endsWith(".js")
                    || url.endsWith(".png")
                    || url.endsWith(".jpg")
                    || url.endsWith("success.jsp")
                    || url.endsWith("index.jsp")
                    || url.endsWith("login.jsp")) {
                chain.doFilter(request, response);
                return;
            }
            String queryString = request.getQueryString();
            if (queryString.endsWith("operation=login")) {
                chain.doFilter(request, response);
                return;
            }


            //1.当前获取到的url
            url = url.substring(1);
            String userUrl = url;

            String method = "";
            //2.当前获取到的查询参数：operation=list       operation=toEdit&id=100
            int index = queryString.indexOf('&');
            if (index != -1) {
                queryString = queryString.substring(0, index);
                method = queryString;
            }
            url = url + "?" + queryString;

            //2.获取到当前登录人允许的操作
            String authorStr = session.getAttribute("authorStr").toString();

            //3.比对本次操作是否在当前登录人允许的操作范围内
            //3.1如果允许，放行
            //3.2不允许跳转到非法访问页
            String username = request.getParameter("username");
            String userIp = request.getRemoteAddr();
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
            long startTime = Long.parseLong(simpleDateFormat.format(date));
            String userId = simpleDateFormat.format(date);
            Date visitTime = date;

            chain.doFilter(request, response);

            Date date2 = new Date();
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMddHHmmssS");
            long endTime = Long.parseLong(simpleDateFormat2.format(date2));
            long executionTime = endTime - startTime;

            if ("addUser".equals(method) || "deleteUser".equals(method) || "updateStatus".equals(method)|| "updateRole".equals(method)) {
                SysLogService sysLogService = (SysLogService) BeanFactory.getBean("sysLogService");
                SysLog sysLog = new SysLog();
                sysLog.setId(userId);
                sysLog.setVisitTime(visitTime);
                sysLog.setUsername(username);
                sysLog.setIp(userIp);
                sysLog.setUrl(userUrl);
                sysLog.setExecutionTime(executionTime);
                sysLog.setMethod(method);
                sysLogService.record(sysLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void destroy() {
    }
}
